<?php
/*
 * Copyright (c) 2021.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */

/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace app\common\model\addon;


use app\common\model\BaseModel;
use app\common\model\platform\PlatformAddon;
use app\common\model\visit\Visit;
use app\common\services\facade\Addons as AddonsServices;
use hiduoke\services\CloudServer;
use think\facade\Cache;

class Addons extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'addons';

    /**
     * 字段类型或者格式转换
     * @var array
     */
    protected $type = [
        'config' => 'json',
    ];

    public $_types = [
        0 => "系统插件",
        1 => "微信公众平台",
        2 => "小程序",
        3 => "企业微信",
        4 => "抖音",
        5 => "独立平台"
    ];

    /**
     * 获取所有的应用标识数组
     * @return array ['dk_qk','dk_bk']
     */
    public function getAllAddonNames()
    {
        $res = $this->field(['name'])->where(['status'=>1])->select();
        $names = [];
        foreach ($res as $key => $value) {
            $names[] = $value['name'];
        }
        return $names;
    }

    /**
     * 获取应用的其他信息通过前端formData数据的Addons，格式为：array(name1=>[auth1],name2=>[auth2])
     * @param $addons
     * @return array
     */
    public function getAddonsByFormDataAddons($addons)
    {
        $names = [];
        foreach ($addons ?? [] as $key => $value) {
            $names[] = $key;
        }
        return $this->getAddonsByNames($names);
    }

    /**
     * 获取应用其他信息通过应用标识数组
     * @param array $names
     * @return array
     */
    public function getAddonsByNames($names = [])
    {
        $data = $this->whereIn('name', $names)->column('*', 'name');
        foreach ($data as $key => $value) {
            $data[$key]['icon'] = $value['icon'] ?: AddonsServices::getAddonsAssetsUrl($value['name']) . "icon.png";
            $auth = get_addons_config($value['name'])['auth'];
            $data[$key]['auth'] = getAddonAuthTree($auth);
            $data[$key]['auth_key_title'] = AddonsServices::getAuthKeyNameByAuth($auth);
            $data[$key]['default_url'] = $this->getAddonDefaultUrl($value['name']);
        }
        return $data;
    }


    /**
     * 获取默认链接
     * @param $name
     * @return bool|string
     */
    public function getAddonDefaultUrl($name, $plaid = 0)
    {
        $config = get_addons_config($name);
        $url = $config['url'] ?? [];
        $param = ['plaid' => $plaid];
        if (isset($url['home']) && is_array($url["home"])) {
            $home = $url["home"];
            $_param = $home["param"] ?? [];
            $default_url = addons_url($home['router'] ?? "index/index", array_merge($param, $_param), $home["suffix"] ?? true, $home['domain'] ?? true, $name);//默认地址
        } else {
            $default_url = addons_url($url['home'] ?? "index/index", $param, true, true, $name);
        }
        return $default_url;
    }

    public function getAddonByName($name)
    {
        return $this->where(['name' => $name])->findOrEmpty();
    }


    public function scopeCount($query)
    {
        $query->whereIn('name', PlatformAddon::getUsefulAddons());
    }


    /*********************************************获取器**********************************************/

    /**
     * 获取应用剩余token次数
     * @param $value
     * @param $data
     * @return mixed|string
     */
    public function getCountMsgAttr($value, $data)
    {
        $cloud_data = (new CloudServer())->getSiteAddonTokenCount();
        return $cloud_data[$data['name']] ?? '';
    }

    /**
     * 获取已用的次数
     * @param $value
     * @param $data
     * @return int
     */
    public function getUsedPlatformCountAttr($value, $data)
    {
        return PlatformAddon::where(['addon_name' => $data['name']])->count();
    }

    /**
     * 获取云端次数
     * @param $value
     * @param $data
     * @return mixed|string
     */
    public function getPlatformCountAttr($value, $data)
    {
        $res = (new CloudServer())->getSiteAddonsCount();
        if ($res['code'] == 0) {
            return $res['data'][$data['name']] ?? '-1';
        } else {
            return '-1';
        }
    }

    /**
     * 获取云端版本
     * @param $value
     * @param $data
     * @return mixed|string
     */
    public function getNewVersionAttr($value, $data)
    {
        return $this->getAddonUpdateMsg()[$data['name']] ?? '';
    }

    public function getAddonUpdateMsg()
    {
        $cache_key = "new_versions";
        $new_versions = Cache::get($cache_key);
        if ($new_versions !== null) {
            return $new_versions;
        } else {
            $addon_names = $this->getAddonNames();
            $CloudServer = new CloudServer();
            if ($CloudServer->getCloudStatus()) {
                $res = $CloudServer->getAddonsVersion($addon_names);
                if ($res['code'] == 0) {
                    Cache::set($cache_key, $res['data'], 3600);
                    return $res['data'];
                }
            }
            return [];
        }
    }

    public function getAddonNames()
    {
        $addons = $this->field(['name'])->select();
        $addon_names = [];
        foreach ($addons as $key => $value) {
            $addon_names[] = $value['name'];
        }
        return $addon_names;
    }

    public function getIsUpdateAttr($val, $data)
    {
        if ($this->new_version) {
            return $this->new_version != $data['version'] ? true : false;
        } else {
            return false;
        }
    }

    /**
     * 默认跳转链接
     * @param $value
     * @param $data
     * @return bool|string
     */
    public function getDefaultUrlAttr($value, $data)
    {
        $url = $this->getAddonDefaultUrl($data['name']);
        return $url;
    }

    /**
     * 获取权限树
     * @param $value
     * @param $data
     * @return array
     */
    public function getAuthAttr($value, $data)
    {
        $auth = get_addons_config($data['name'])['auth'] ?? [];
        return getAddonAuthTree($auth);
    }

    /**
     * 获取应用权限集
     * @param $value
     * @param $data
     * @return array
     */
    public function getAuthKeyTitleAttr($value, $data)
    {
        $auth = get_addons_config($data['name'])['auth'] ?? [];
        return AddonsServices::getAuthKeyNameByAuth($auth);
    }

    /**
     * 获取图标
     * @param $value
     * @param $data
     * @return mixed|string
     */
    public function getIconAttr($value, $data)
    {
        return $data['icon'] ?: AddonsServices::getAddonsAssetsUrl($data['name']) . "icon.png";
    }

    /**
     * 类型名称
     * @param $value
     * @param $data
     * @return string
     */
    public function getTypeNameAttr($value, $data)
    {
        return $this->_types[$data['type']];
    }

    public function getTodayVisitAttr($value, $data)
    {
        return (new Visit())->where('name', $data['name'])->where('date', date('Ymd', time()))->value('count');
    }

    public function getYesterdayVisitAttr($value, $data)
    {
        return (new Visit())->where('name', $data['name'])->where('date', date('Ymd', strtotime('-1 day')))->value('count');
    }

    public function getVisitAttr($value, $data)
    {
        return (new Visit())->where('name', $data['name'])->sum('count');
    }
}
